//
//  FGWelcomeView.swift
//  飞哥大微博
//
//  Created by huangfei on 2017/6/9.
//  Copyright © 2017年 huangfei. All rights reserved.
//

import UIKit
import SDWebImage

/// 欢迎视图
class FGWelcomeView: UIView {

    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    func welComeView() -> FGWelcomeView {
        let nib = UINib(nibName: "FGWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! FGWelcomeView
        // 从 XIB 加载的视图，默认是 600*600 的
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        // 1> url
        guard let urlString = FGNetworkManager.shared.userAccount.avatar_large,
            let url = URL(string: urlString) else {
                return
        }
        // 2> 设置头像
        iconView.sd_setImage(with: url, placeholderImage: UIImage(named:"avatar_default_big"))
        iconView.layer.cornerRadius = iconView.bounds.width * 0.5
        iconView.layer.masksToBounds = true
    }
    
    /// 视图被添加到 window 上，表示视图已经显示
    override func didMoveToWindow() {
        super.didMoveToWindow()
        // - layoutIfNeeded 会直接按照当前的约束直接更新控件位置
        // - 执行之后，控件所在位置，就是 XIB 中布局的位置
        layoutIfNeeded()
        
        bottomCons.constant = bounds.size.height - 200
        
        // 如果控件们的 frame 还没有计算好，所有的约束会一起动画
        UIView.animate(withDuration: 1.0,
                       delay: 0,
                       usingSpringWithDamping: 0.7,
                       initialSpringVelocity: 0,
                       options: [],
                       animations: { 
                        // 更新约束
                        self.layoutIfNeeded()
        }) { (_) in
            UIView.animate(withDuration: 1.0, animations: { 
                self.tipLabel.alpha = 1
            }, completion: { (_) in
                // 动画结束后移除欢迎界面
                self.removeFromSuperview()
            })
        }
        
    }
}
